package org.lex.splitter.ui.console;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import org.apache.log4j.Logger;
import org.lex.splitter.core.Splitter;

public class ConsoleSplit {
	public static final String USAGE = ConsoleSplit.class.getSimpleName() + " <input file>";
	private static final String USER_DIR = "user.dir";

	public static void main(String[] args) {
		// System.getProperties().list(System.err);
		new ConsoleSplit(args).run();
	}

	private Logger log = Logger.getLogger(ConsoleSplit.class);
	private String[] args = null;

	public ConsoleSplit(String[] args) {
		log.info("args=" + Arrays.toString(args));
		this.args = args;
	}

	public void run() {
		File file = this.parseInputFile(args);
		if (null == file) {
			log.error("File not found.");
			return;
		}

		Splitter split = new Splitter();
		try {
			split.split(file);
		} catch (IOException e) {
			log.error("Split failed", e);
		}
	}

	private File parseInputFile(String[] args) {
		if (null == args || 0 == args.length) {
			log.error("No input, exit.");
			System.err.println(USAGE);
			return null;
		}

		String arg = args[0];
		File file = new File(arg);
		if (false == exists(file)) {
			log.info("Absolute File not found, try relate path...");
			String userDir = System.getProperty(USER_DIR, ".");
			file = new File(userDir, arg);
			if (false == exists(file)) {
				file = null;
			}
		}
		log.info("Parse Input File=" + file);
		return file;
	}

	private boolean exists(File file) {
		return (file.exists() && file.isFile());
	}
}
